package com.sigmatrix.h5.redisson;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;

import com.sigmatrix.h5.utils.Assert;

/**
 * 分布式对象。
 * 
 * @author wei.wang
 *
 */
public class DistributedObject {

	private final static String QUEUE_PREFIX = "queue:";

	private RedissonClient redissonClient;

	public <T> boolean offer(String queueName, T obj) {
		Assert.notNull(queueName, "队列名不可以为null");
		Assert.notNull(obj, "插入值为空");
		RBlockingQueue<T> queue = redissonClient.getBlockingQueue(QUEUE_PREFIX + queueName);
		return queue.offer(obj);
	}

	/**
	 * Retrieves, but does not remove
	 * 
	 * @param queueName
	 * @return
	 */
	public <T> T peek(String queueName) {
		Assert.notNull(queueName, "队列名不可以为null");
		RBlockingQueue<T> queue = redissonClient.getBlockingQueue(QUEUE_PREFIX + queueName);
		return queue.peek();
	}

	/**
	 * Retrieves, remove
	 * 
	 * @param queueName
	 * @return
	 */
	public <T> T poll(String queueName) {
		Assert.notNull(queueName, "队列名不可以为null");
		RBlockingQueue<T> queue = redissonClient.getBlockingQueue(QUEUE_PREFIX + queueName);
		return queue.poll();
	}

	public <T> T poll(String queueName, long timeout, TimeUnit unit) throws InterruptedException {
		Assert.notNull(queueName, "队列名不可以为null");
		RBlockingQueue<T> queue = redissonClient.getBlockingQueue(QUEUE_PREFIX + queueName);
		return queue.poll(timeout, unit);
	}

	public RedissonClient getRedissonClient() {
		return redissonClient;
	}

	public void setRedissonClient(RedissonClient redissonClient) {
		this.redissonClient = redissonClient;
	}

}
